﻿using Entity;
using IService;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging; // 引入命名空间
namespace XingWeiDaWMSProject.Controllers
{
    public class WarehouseController : Controller
    {
        private readonly IWarehouseService _warehouseService;
        private readonly IStorageLocationService _storageLocationService;
        private readonly ILogger<WarehouseController> _logger; // 新增日志字段
        public WarehouseController(IWarehouseService warehouseService, IStorageLocationService storageLocationService, ILogger<WarehouseController> logger)
        {
            _warehouseService = warehouseService;
            _storageLocationService = storageLocationService;
            _logger = logger;
        }

        // 新增仓库页面（传递组织和库位主管用户）
        public async Task<IActionResult> Add()
        {
            ViewBag.Organizations = await _warehouseService.GetAllOrganizations();
            ViewBag.WarehouseManagers = await _warehouseService.GetWarehouseManagersAsync();
            ViewBag.WarehouseStatusList = await _warehouseService.GetWarehouseStatusListAsync();
            _logger.LogInformation("控制器传递到视图的状态列表数量：{Count}",
      (ViewBag.WarehouseStatusList as List<WarehouseStatusDTO>)?.Count ?? 0);
            return View();
        }

        // 新增仓库提交接口
        [HttpPost]
        public async Task<IActionResult> Add([FromBody] WarehouseAddDTO dto)
        {
            try
            {
                // 参数校验
                if (dto == null)
                    return Json(new { code = 400, message = "请求参数不能为空" });
                if (string.IsNullOrWhiteSpace(dto.WarehouseNumber))
                    return Json(new { code = 400, message = "仓库编号不能为空" });
                if (string.IsNullOrWhiteSpace(dto.WarehouseName))
                    return Json(new { code = 400, message = "仓库名称不能为空" });
                if (dto.WarehouseCapacity <= 0)
                    return Json(new { code = 400, message = "仓库容量必须大于0" });
                if (dto.OrgId <= 0)
                    return Json(new { code = 400, message = "请选择库管部门" });
                if (dto.ManagerId <= 0)
                    return Json(new { code = 400, message = "请选择仓库主管" });
                if (dto.SelectedLocationIds == null || dto.SelectedLocationIds.Count == 0)
                    return Json(new { code = 400, message = "请至少选择一个库位" });

                await _warehouseService.AddWarehouseAsync(dto);
                return Json(new { code = 200, message = "新增仓库成功" });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"新增仓库异常：{ex.Message}\n{ex.StackTrace}");
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }

        // 仓库列表页
        public async Task<IActionResult> Index()
        {
            ViewBag.Organizations = await _warehouseService.GetAllOrganizations();
            ViewBag.WarehouseManagers = await _warehouseService.GetWarehouseManagersAsync();
            ViewBag.WarehouseStatusList = await _warehouseService.GetWarehouseStatusListAsync();
            return View();
        }

        // 仓库分页查询接口
        [HttpGet]
        public async Task<IActionResult> GetPageList(
    string warehouseName,
    int? warehouseStatus,
    int? organizationId,
    string warehouseManager,
    int pageIndex = 1,
    int pageSize = 10
)
        {
            try
            {
                Console.WriteLine($"【GetPageList】查询参数: warehouseName={warehouseName}, warehouseStatus={warehouseStatus}, organizationId={organizationId}, warehouseManager={warehouseManager}, pageIndex={pageIndex}, pageSize={pageSize}");

                var pagination = new PaginationQuery { PageIndex = pageIndex, PageSize = pageSize };
                var result = await _warehouseService.GetWarehousePageListAsync(
                    warehouseName, warehouseStatus, organizationId, warehouseManager, pagination);

                Console.WriteLine($"【GetPageList】查询结果: 总数={result.TotalCount}, 数据条数={result.Data?.Count ?? 0}");

                // 如果有数据，打印第一条数据的详细信息
                if (result.Data != null && result.Data.Any())
                {
                    var firstItem = result.Data.First();
                    Console.WriteLine($"【GetPageList】第一条数据: ID={firstItem.warehouse_id}, Number={firstItem.warehouse_number}, Name={firstItem.warehouse_name}");
                }

                return Json(new
                {
                    code = 200,
                    data = new
                    {
                        data = result.Data,
                        totalCount = result.TotalCount,
                        totalPages = result.TotalPages,
                        pageIndex = result.PageIndex,
                        pageSize = result.PageSize
                    },
                    message = "仓库查询成功"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【GetPageList】异常: {ex.Message}");
                return Json(new { code = 500, message = $"仓库查询失败：{ex.Message}" });
            }
        }

        // 库位相关接口（保持不变）
        [HttpGet]
        public async Task<IActionResult> GetStorageLocationPagedList(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var pagination = new PaginationQuery { PageIndex = pageIndex, PageSize = pageSize };
                var result = await _storageLocationService.GetPagedListAsync(pagination);

                return Json(new
                {
                    code = 200,
                    data = new
                    {
                        data = result.Data,
                        totalCount = result.TotalCount,
                        totalPages = result.TotalPages,
                        pageIndex = result.PageIndex,
                        pageSize = result.PageSize
                    },
                    message = "库位查询成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, message = $"库位查询失败：{ex.Message}" });
            }
        }

        // 删除单个库位
        [HttpPost]
        public async Task<IActionResult> DeleteStorageLocation(int id)
        {
            try
            {
                if (id <= 0)
                    return Json(new { code = 400, message = "库位ID必须大于0" });

                await _storageLocationService.DeleteAsync(id);
                return Json(new { code = 200, message = "库位删除成功" });
            }
            catch (KeyNotFoundException ex)
            {
                return Json(new { code = 404, message = ex.Message });
            }
            catch (InvalidOperationException ex)
            {
                return Json(new { code = 400, message = ex.Message }); // 业务校验失败
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除库位异常，ID：{Id}", id);
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }

        // 批量删除库位
        [HttpPost]
        public async Task<IActionResult> DeleteBatchStorageLocation([FromBody] int[] ids)
        {
            try
            {
                if (ids == null || ids.Length == 0)
                    return Json(new { code = 400, message = "请选择至少一个库位" });

                await _storageLocationService.DeleteBatchAsync(ids);
                return Json(new { code = 200, message = "库位批量删除成功" });
            }
            catch (ArgumentException ex)
            {
                return Json(new { code = 400, message = ex.Message });
            }
            catch (InvalidOperationException ex)
            {
                return Json(new { code = 400, message = ex.Message }); // 业务校验失败
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除库位异常，IDs：{Ids}", string.Join(",", ids));
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }
        // 新增库位
        [HttpPost]
        public async Task<IActionResult> AddStorageLocation([FromBody] StorageLocationDTO dto)
        {
            try
            {
                // 参数校验
                if (dto == null)
                    return Json(new { code = 400, message = "请求参数不能为空" });
                if (string.IsNullOrWhiteSpace(dto.LocationNumber))
                    return Json(new { code = 400, message = "库位编号不能为空" });
                if (string.IsNullOrWhiteSpace(dto.LocationName))
                    return Json(new { code = 400, message = "库位名称不能为空" });
                if (dto.LocationCapacity <= 0)
                    return Json(new { code = 400, message = "库位容量必须大于0" });
                if (dto.LocationManager <= 0)
                    return Json(new { code = 400, message = "请选择库位主管" });

                var newId = await _storageLocationService.AddAsync(dto);
                return Json(new { code = 200, message = "库位新增成功", data = new { locationId = newId } });
            }
            catch (InvalidOperationException ex)
            {
                return Json(new { code = 400, message = ex.Message }); // 编号重复等业务异常
            }
            catch (ArgumentException ex)
            {
                return Json(new { code = 400, message = ex.Message }); // 参数校验失败
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增库位异常，编号：{Number}", dto?.LocationNumber);
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }
        /// <summary>
        /// 删除单个仓库
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                if (id <= 0)
                    return Json(new { code = 400, message = "仓库ID必须大于0" });

                await _warehouseService.DeleteWarehouseAsync(id);
                return Json(new { code = 200, message = "仓库删除成功" });
            }
            catch (KeyNotFoundException ex)
            {
                return Json(new { code = 404, message = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除仓库异常，ID：{Id}", id);
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }
        /// <summary>
        /// 批量更新仓库状态（锁定/启用/停用）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchUpdateStatus(string ids, int status)
        {
            try
            {
                // 1. 参数校验
                if (string.IsNullOrEmpty(ids))
                    return Json(new { code = 400, message = "请选择需要操作的仓库" });

                var warehouseIds = ids.Split(',')
      .Select(s =>
      {
          int.TryParse(s, out int id);
          return (s, id); // 返回原始字符串和解析结果
      })
      .Where(t => int.TryParse(t.s, out _)) // 筛选可解析的ID
      .Select(t => t.id)
      .ToList();

                if (!warehouseIds.Any())
                    return Json(new { code = 400, message = "仓库ID格式错误" });

                // 2. 调用服务层
                var result = await _warehouseService.BatchUpdateStatusAsync(warehouseIds, status);

                // 3. 返回结果
                return result.Success
                    ? Json(new { code = 200, message = result.Message })
                    : Json(new { code = 400, message = result.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量更新仓库状态异常，IDs：{Ids}，Status：{Status}", ids, status);
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }
        /// <summary>
        /// 获取仓库详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDetail(int id)
        {
            try
            {
                if (id <= 0)
                    return Json(new { code = 400, message = "仓库ID必须大于0" });

                var warehouse = await _warehouseService.GetWarehouseDetailAsync(id);
                if (warehouse == null)
                    return Json(new { code = 404, message = "未找到指定仓库" });

                return Json(new { code = 200, data = warehouse, message = "获取仓库详情成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取仓库详情异常，ID：{Id}", id);
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }
        /// <summary>
        /// 编辑仓库页面
        /// </summary>
        public async Task<IActionResult> Edit(int id)
        {
            try
            {
                if (id <= 0)
                    return RedirectToAction("Index");

                // 1. 获取仓库编辑数据
                var warehouse = await _warehouseService.GetWarehouseForEditAsync(id);
                ViewBag.Warehouse = warehouse;

                // 2. 传递下拉列表数据（与新增页面一致）
                ViewBag.Organizations = await _warehouseService.GetAllOrganizations();
                ViewBag.WarehouseManagers = await _warehouseService.GetWarehouseManagersAsync();
                ViewBag.WarehouseStatusList = await _warehouseService.GetWarehouseStatusListAsync();

                return View();
            }
            catch (KeyNotFoundException ex)
            {
                TempData["Error"] = ex.Message;
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载编辑页面失败，ID：{Id}", id);
                TempData["Error"] = $"加载失败：{ex.Message}";
                return RedirectToAction("Index");
            }
        }

        /// <summary>
        /// 提交编辑仓库
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Edit([FromBody] WarehouseEditDTO dto)
        {
            if (!ModelState.IsValid)
                return Json(new { code = 400, message = "参数校验失败" });

            try
            {
                var result = await _warehouseService.UpdateWarehouseAsync(dto);
                return result.Success
                    ? Json(new { code = 200, message = result.Message })
                    : Json(new { code = 400, message = result.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "提交编辑仓库失败，ID：{Id}", dto.WarehouseId);
                return Json(new { code = 500, message = $"系统异常：{ex.Message}" });
            }
        }
    }

   
}